define(function (require) {
    require('../../../c/base/index');
    require('../../../c/nav/index');

    require('./actCategory-list-tpl');
    var actCategoryTpl = juicer.templates['actCategory-list.juicer.html'];

    var category = {
        init: function () {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function () {
                if ($(this).parents("a").text() == "外店类目管理") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            var currentCityCode = CRM.getUrlParam('cityCode');
            this.initCityList(currentCityCode);
            this.bindEvent();
        },
        /*
        初始化城市下拉选项并搜索
         */
        initCityList: function (cityCode) {
            var self = this;
            CRM.request({
                "type": "POST",
                "url": CRM.getOuterUrl('/shop/city/queryOpenCity'),
                "dataType": "json",
                "contentType": 'application/json',
                "data": JSON.stringify({
                }),
                "success": function (req) {
                    var listStr = "";
                    var city = "";
                    var arr = [];
                    if (req.status){
                        for (var i = 0;i < req.entry.length;i++){
                            listStr += '<option value="' + req.entry[i].cityCode +'">' + req.entry[i].city + '</option>';
                            arr.push(req.entry[i].cityCode + "");
                        }
                        $("#city").html(listStr);
                        // console.log(cityCode);
                        // console.log(typeof cityCode);
                        // console.log(typeof arr[1]);
                        if (arr.indexOf(cityCode) == -1){
                            //console.log('ooo');
                            city = req.entry[0].cityCode;
                        } else {
                            city = cityCode;
                        }
                        //city = (arr.indexOf(cityCode) > -1) ? cityCode : req.entry[0].cityCode;
                        //console.log(city);
                        $("#city").val(city);
                    } else {
                        CRM.showDialog(req.message);
                    }
                    self.queryByCities();
                },
                "error": function (req) {
                    CRM.showDialog(req.message);
                }
            });
        },
        /*
        查询类目列表
         */
        queryByCities: function () {
            var currentCity = $("#city").val();
            CRM.request({
                "type": "GET",
                "url": CRM.getOuterUrl("/itemcenter/crm/frontCategory/actcat/list"),
                "dataType": "json",
                "data": {
                    "cityCode": currentCity,
                    "t": (new Date()).getTime()
                },
                "success": function (req) {
                    //console.log(req.status);
                    if (req.status){
                        if (req.entry.length > 0){
                            //console.log(actCategoryTpl);
                            var html = actCategoryTpl({data:req.entry});
                            //console.log(html);
                            var listNum = req.entry.length;
                            //console.log(listNum);
                            $("#addActCategory").attr('data-listAmount',listNum);
                            $("#listContainer").html(html);
                        }else {
                            var noResult = '<tr><td valign="top" colspan="3" style="text-align: center;">没有匹配的结果</td></tr>';
                            $("#listContainer").html(noResult);
                        }
                    } else {
                        CRM.showDialog(req.message);
                    }
                },
                "error": function (req) {
                    CRM.showDialog(req.message);
                }
            });
        },
        /*
        添加类目框弹出,限制添加类目条数
         */
        showAddModal: function () {
            //var listAmount = $("#addActCategory").attr('data-listAmount');
            if ($("#addConfirm").attr("data-type") == "add"){
                $("#add_category_dialog_title").text("添加活动类目");
                //$("#categoryName").attr('readonly',false);
            }else if ($("#addConfirm").attr("data-type") == "edit"){
                $("#add_category_dialog_title").text("编辑活动类目");
                //$("#categoryName").attr('readonly',true);
            }
            // if (listAmount > 5 && $("#addConfirm").attr("data-type") == "add"){
            //     CRM.showDialog("最多可同时存在6个活动类目");
            //     //$("#add_category_dialog").modal("show");
            // }else {
            $("#add_category_dialog").modal("show");
                //CRM.showDialog("最多可同时存在6个活动类目");
            // }
        },
        /*
        删除类目确认框
         */
        showDelModal: function (id,name) {
            $("#savedId").val(id);
            $("#cateNameInfo").text(name);
            $("#confirm_dialog").modal('show');
        },
        /*
        添加或编辑活动类目
         */
        addActCategory: function (dataString) {
            var self = this;
            if (/^[\u4e00-\u9fa5]+$/.test(dataString.name) && /^\d{0,3}$/.test(dataString.sort)){
                CRM.request({
                    "type": "GET",
                    "url": CRM.getOuterUrl("/itemcenter/crm/frontCategory/actcat/save"),
                    "dataType": "json",
                    "data": dataString,
                    //     JSON.stringify({
                    //     "cityCode": $("#city").val(),
                    //     "cityName": $("#city").find("option:selected").text(),
                    //     "id": id
                    // }),
                    "success": function (req) {
                        if (req.status){
                            if ($("#addConfirm").attr("data-type") == "add"){
                                CRM.showDialog("添加成功");
                            } else if ($("#addConfirm").attr("data-type") == "edit"){
                                CRM.showDialog("修改成功");
                            }
                            $("#add_category_dialog").modal("hide");
                            self.queryByCities();
                        }else {
                            CRM.showDialog(req.message);
                        }
                    },
                    "error": function (req) {
                        CRM.showDialog("添加失败");
                    }
                });
            } else {
                CRM.showDialog("输入格式有误");
            }
        },
        /*
        删除类目
         */
        delActCategory: function (actId) {
            var self = this;
            CRM.request({
                "type": "GET",
                "url": CRM.getOuterUrl("/itemcenter/crm/frontCategory/actcat/delete"),
                "dataType": "json",
                "data": {
                    "id": actId
                },
                "success": function (req) {
                    if (req.status){
                        CRM.showDialog("删除成功");
                        self.queryByCities();
                        $("#confirm_dialog").modal('hide');
                    }else {
                        CRM.showDialog(req.message);
                    }
                },
                "error": function (req) {
                    CRM.showDialog("删除失败");
                }
            });
        },
        /*
        事件绑定
         */
        bindEvent: function () {
            var self = this;
            //城市选择绑定查询
            $("#city").on('change',function () {
                var cityId = $("#city").val();
                self.queryByCities(cityId);
            });
            //添加活动类目绑定对应弹出框
            $("#addActCategory").on('click',function () {
                $("#addConfirm").attr("data-type","add");
                $("#addConfirm").attr('data-id','');
                $("#categoryName").val('');
                $("#sort").val('');
                self.showAddModal();
            });
            //编辑类目名称绑定弹出层
            $("#listContainer").on('click','.editActName',function (e) {
                var target = $(e.currentTarget);
                //console.log(target);
                var listId = target.parent().attr('data-id');
                var listName = $("#listContainer span[data-nid='" + listId +"']").text();
                var sort = $("#listContainer span[data-id="+ listId + "]").text();
                $("#addConfirm").attr('data-type','edit');
                $("#addConfirm").attr('data-id',listId);
                $("#categoryName").val(listName);
                $("#sort").val(sort);
                self.showAddModal();
                // var cityCode = $("#city").val();
                // var cityName = $("#city").find("option:selected").text();
            });
            //添加或编辑活动类目绑定
            $("#addConfirm").on('click',function () {
                var categoryName = $("#categoryName").val();
                var cityCode = $("#city").val();
                var cityName = $("#city").find("option:selected").text();
                var id = $("#addConfirm").attr("data-id");
                var dataString = "";
                if ($("#addConfirm").attr("data-type") == "add"){
                    dataString = {
                        "cityCode": cityCode,
                        "cityName": cityName,
                        "name":categoryName,
                        "sort": $("#sort").val()
                    };
                } else if ($("#addConfirm").attr("data-type") == "edit"){
                    dataString = {
                        "cityCode": cityCode,
                        "cityName": cityName,
                        "name": categoryName,
                        "id": id,
                        "sort": $("#sort").val()
                            //$("#listContainer span[data-id="+ id + "]").text()
                    };
                }
                self.addActCategory(dataString);
            });
            //删除类目绑定对应弹出框
            $("#listContainer").on('click','.delActList',function (e) {
                var target = $(e.currentTarget);
                var targetId = target.parent().attr('data-id');
                var targetName = target.parent().attr('data-name');
                self.showDelModal(targetId,targetName);
            });
            /*
            删除绑定
             */
            $("#confirm").on('click',function (e) {
                var target = $(e.currentTarget);
                var targetInput = target.siblings('input');
                var targetId = targetInput.val();
                self.delActCategory(targetId);
            });
            //商品管理页面跳转
            $("#listContainer").on('click','.actGoodsManage',function (e) {
                var target = $(e.currentTarget);
                var targetCId = target.parent().attr('data-cid');
                var targetId = target.parent().attr('data-id');
                var targetName = $("#listContainer span[data-nid='" + targetId +"']").text();
                //console.log(targetName);
                location.href = CRM.getOuterUrl('/crm/www/outflat/categoryGoods.html') + '?actcatId=' + targetCId + "&actcatName=" + targetName + "&cityCode=" + $("#city").val();
            })
        }
    };

    category.init();
});